<?php
/**
 * Class used to manipulate files and folders
 *
 * @author André Silva
 */
class File {
	/**
	 * @var string
	 */
	protected $fileName;

	public function __construct($file) {
		if(!file_exists($file)) {
			throw new Exception('File not found');
		}
		if($file == '.' || $file == '..') {
			throw new Exception('Invalid file');
		}

		$this->fileName = $file;
	}

	/**
	 * Try to copy the current file or folder
	 * @param string $path
	 */
	public function copy($path) {
		if (is_dir($this->fileName)) {
			throw new Exception('Failed to copy: '.$this->fileName.' is a directory');
		}
		if(!file_exists(dirname($path))) {
			mkdir(dirname($path), 0755, true);
		}
		if(!copy($this->fileName, $path)) {
			throw new Exception('Failed to copy: '.$this->fileName);
		}
	}

	/**
	 * Try to delete the current file or folder
	 * @param string $path
	 */
	public function delete($path = null) {
		if ($path === null) {
			$path = $this->fileName;
		}
		if(file_exists($path) && $path != '.' && $path != '..') {
			if(is_dir($path)) {
				$files = scandir($path);
				natcasesort($files);
				if( count($files) > 2 ) { // '.' and '..'
					foreach( $files as $file ) {
						if($file != '.' && $file != '..') {
							$this->delete($path.DIRECTORY_SEPARATOR.$file);
						}
					}
				}
				rmdir($path);
			} else {
				unlink($path);
			}
		}
	}

	/**
	 * Get the filename
	 * @return string
	 */
	public function getFileName() {
		return $this->fileName;
	}
}
?>
